package com.steve.combat.algorithm.douyin;

import java.util.*;

/**
 * @Author: STEVE
 * @Description: 单词匹配器
 * @since: 2025-04-18
 */
public class WordMatcher {

    private final List<String> words;
    private final Map<String, List<Integer>> index;

    public WordMatcher(List<String> words) {
        this.words = words;
        this.index = new HashMap<>();
        buildIndex();
    }

    private void buildIndex() {
        for (int i = 0; i < words.size(); i++) {
            String word = words.get(i);
            if (word == null || word.isEmpty()) {
                continue; // 跳过空单词
            }
            String firstChar = String.valueOf(word.charAt(0)).toLowerCase();
            String lastChar = String.valueOf(word.charAt(word.length() - 1)).toLowerCase();
            String key = firstChar + lastChar;

            index.computeIfAbsent(key, k -> new ArrayList<>()).add(i);
        }
    }

    public List<Integer> findMatchingPositions(char firstChar, char lastChar) {
        String key = String.valueOf(Character.toLowerCase(firstChar)) +
                String.valueOf(Character.toLowerCase(lastChar));
        return index.getOrDefault(key, new ArrayList<>());
    }

    public String getWordAtPosition(int position) {
        if (position >= 0 && position < words.size()) {
            return words.get(position);
        }
        return null;
    }

    // 测试用例
    public static void main(String[] args) {
        List<String> words = Arrays.asList("apple", "banana", "orange", "ape", "Animal", "algorithm", "goal");
        WordMatcher matcher = new WordMatcher(words);

        // 测试查找
        System.out.println(matcher.findMatchingPositions('a', 'e')); // 输出: [0, 3] (apple和ape)
        System.out.println(matcher.findMatchingPositions('b', 'a')); // 输出: [1] (banana)
        System.out.println(matcher.findMatchingPositions('A', 'l')); // 输出: [4, 5] (Animal和algorithm)
        System.out.println(matcher.findMatchingPositions('x', 'y')); // 输出: [] (无匹配)

        // 获取具体单词
        System.out.println(matcher.getWordAtPosition(2)); // 输出: "orange"
    }

}
